const path = require('path');
const fs = require('fs');
const { getHeader, setHeader } = require('./helper')

module.exports = (message, env) => {
    if(message.request.status){
        return message;
    }

    if(message.request.method !== 'GET'){
        return message;
    }

    if(message.request.path.indexOf('.') === 0){
        message.response.status = 403;
        return message;
    }

    const targetPath = path.resolve(env.root + message.request.path);
    if(!fs.existsSync(targetPath)){
        message.response.status = 404;
        return message;
    }

    const requestPathStat = fs.statSync(targetPath);
    if(requestPathStat.isFile()){
        // check-if-none-match
        const requestEtag = getHeader(message.request.headers, 'If-None-Match');
        if(requestEtag && requestEtag.trim() === requestPathStat.mtimeMs.toString(16) + requestPathStat.size.toString(16)){
            message.response.status = 304;
            return message;
        }
    }

    // 正常返回三个header
    setHeader(message.response.headers, 'Cache-Control', 'max-age:3600');
    setHeader(message.response.headers, 'Etag', requestPathStat.mtimeMs.toString(16) + requestPathStat.size.toString(16));
    setHeader(message.response.headers, 'Last-Modified', requestPathStat.mtime);
    return message;
}